<?php

Raise::load('core.RaisePage');
Raise::load('core.RaiseCache');

/**
 * RaiseCachablePage abstract class
 * A RaisePage that can be cached
 *
 * @author Sam-Mauris Yong <hellclanner at live dot com>
 * @license http://www.opensource.org/licenses/bsd-license New BSD License
 * @package Raise.Core.Caching
 * @since 1.2
 */
abstract class RaiseCachablePage extends RaisePage {

    /**
     * Cache store of this page
     * @var RaiseCache
     */
    private $cache;

    /**
     * Get or set the period of time that this cache should live
     * @param RaiseTimeSpan $c (optional) If this parameter is passed in, it will set the new value.
     * @return RaiseTimeSpan
     */
    protected function cacheLife($c){
        if(func_num_args() == 1){
            $this->cache->cacheLife($c);
        }
        return $this->cache->cacheLife();
    }

    /**
     * Get or set the unique identifier of this cachable
     * @param integer $c (optional) If this parameter is passed in, it will set the new value.
     * @return integer
     */
    protected function cacheId($c){
        if(func_num_args() == 1){
            $this->cache->cacheId($c);
        }
        return $this->cache->cacheId();
    }

    /**
     * Construct and prepare output into the response class
     * Output will only be reconstructed if the cache is not available or reset
     * otherwise output will be from the cache
     */
    public function output(){
        $cache = $this->cache->load();
        $this->application()->response()->headers()->add('ETag', RaiseHashDigest::sha256(get_class($this)), true);
        $this->application()->response()->headers()->add('Last-Modified', $this->cache->file()->getLastModified()->toRFC822(), true);
        $this->application()->response()->headers()->add('Expires', $this->cache->expiry()->toRFC822(), true);
        if($cache != null){
            $this->application()->response()->body = $cache;
        }else{
            parent::output();
            $this->cache->save($this->response()->body);
        }
    }

}
